package com.cqfae.deploycentral.app.services.impl;

import com.cqfae.deploycentral.api.utils.IdGenerator;
import com.cqfae.deploycentral.app.dao.entity.ApproveDocument;
import com.cqfae.deploycentral.app.dao.entity.ExpectPublishEnqueue;
import com.cqfae.deploycentral.app.dao.entity.ReportTestLink;
import com.cqfae.deploycentral.app.dao.entity.WindowPlans;
import com.cqfae.deploycentral.app.dao.mapper.ApproveDocumentMapper;
import com.cqfae.deploycentral.app.dao.mapper.ConstantCodeMapper;
import com.cqfae.deploycentral.app.dao.mapper.ExpectPublishEnqueueMapper;
import com.cqfae.deploycentral.app.dao.mapper.WindowPlansMapper;
import com.cqfae.deploycentral.app.services.ExpectPublishEnqueueService;
import com.cqfae.deploycentral.app.services.JiraService;
import com.cqfae.deploycentral.app.services.ReportInfoService;
import com.cqfae.deploycentral.app.utils.JiraAPIUtil;
import com.cqfae.deploycentral.app.web.response.JiraInfo;
import com.cqfae.deploycentral.app.web.vo.SelectedVo;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.cqfae.deploycentral.app.base.BaseConstantCode.*;
import static org.springframework.util.Assert.isTrue;

@Service
@Transactional
public class JiraServiceImpl implements JiraService {


    @Autowired
    private JiraAPIUtil jiraAPIUtil;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private ApproveDocumentMapper approveDocumentMapper;

    @Autowired
    private ReportInfoService reportInfoService;

    @Autowired
    private ExpectPublishEnqueueMapper expectPublishEnqueueMapper;

    @Autowired
    private ExpectPublishEnqueueService expectPublishEnqueueService;

    @Autowired
    private ConstantCodeMapper constantCodeMapper;

    @Autowired
    private WindowPlansMapper windowPlansMapper;

    @Override
    public List<SelectedVo> getReadyForReleasedVersionToApprove(){
        List<JiraInfo> jiraInfos = jiraAPIUtil.getReadyForReleasedVersion();
        List<SelectedVo> selectedVos = new CopyOnWriteArrayList<>();
        //去重
        for(JiraInfo jiraInfo:jiraInfos){
            Example example = new Example(ApproveDocument.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("jiraVersionId",jiraInfo.getVersionId());
            List<ApproveDocument> approveDocuments = approveDocumentMapper.selectByExample(example);
            SelectedVo selectedVo = new SelectedVo();
            if(approveDocuments.isEmpty()){
                selectedVo.setCode(jiraInfo.getCode()+"");
                selectedVo.setName(jiraInfo.getName());
            }else{
                selectedVo = checkIsRepeat(jiraInfo,approveDocuments);
            }
            selectedVos.add(selectedVo);
        }
        return selectedVos;
    }

    /**
     * 传入一个jiraVersion的信息进来，判断后，成功就包装成选项，失败就传出空
     * 判断依据 1.不存在任何一个审批流程中
     *          2.存在流程中但查询的所有值均为不同意状态
     * @param jiraInfo
     * @param approveDocuments
     * @return
     */
    public SelectedVo checkIsRepeat(JiraInfo jiraInfo,List<ApproveDocument> approveDocuments){
        SelectedVo selectedVo = new SelectedVo();
        for(ApproveDocument approveDocument:approveDocuments){
            if(APPROVE_STATUS_FAIL_CODE == approveDocument.getApproveStatus()) {
                selectedVo.setCode(jiraInfo.getCode()+"");
                selectedVo.setName(jiraInfo.getName());
            }
        }
        return selectedVo;
    }

    @Override
    public List<JiraInfo> getReadyForReleasedVersion(){
        return jiraAPIUtil.getReadyForReleasedVersion();
    }

    @Override
    public List<JiraInfo> getDetailInfoReVersion(){
        return jiraAPIUtil.geDetailInfoReVersion();
    }

    @Override
    public JiraInfo getOneInfoReVersion(Long versionId){
        return jiraAPIUtil.getOneInfoReVersion(versionId);
    }

    @Override
    public int changeVersionStatus(String reportCode){
        int executeResult = SCHEDULED_EXEC_NOTHING;
        //Step2 根据测试报告号查询评审信息中的上线时间(onlineTime)
        WindowPlans windowPlans = new WindowPlans();
        windowPlans.setReportCode(reportCode);
        List<WindowPlans> windowPlansList = windowPlansMapper.select( windowPlans );
        if(windowPlansList.isEmpty()){
            isTrue(false, "测试报告"+reportCode+"版本并无对应的上线时间，请核实后修改");
            return SCHEDULED_EXEC_FAIL;
        }
        Integer windowDate = 20170101;
        for(WindowPlans windowPlans1:windowPlansList){
            windowDate = windowPlans1.getWindowDate();
        }
        StringBuilder windowDateStringBuilder =  new StringBuilder();
        windowDateStringBuilder.append(windowDate);
        windowDateStringBuilder.insert(4,"-");
        windowDateStringBuilder.insert(7,"-");

        String releaseDate =  windowDateStringBuilder +"T00:00:00.000+08:00";
        //Step3 判断该版本是否已经发布（支持多个版本同时修改）
        List<ReportTestLink> reportTestLinkList = reportInfoService.getReportTestLink(reportCode);
        List<JiraInfo> readyForReleasedVersionList = jiraAPIUtil.getReadyForReleasedVersion();
        for(ReportTestLink reportTestLink:reportTestLinkList){
            for(JiraInfo jiraInfo:readyForReleasedVersionList){
                if(jiraInfo.getVersionId().longValue() == reportTestLink.getVersionId().longValue()){
                    jiraInfo.setReleaseDate(DateTime.parse(releaseDate));
                    executeResult = jiraAPIUtil.changeVersionStatus( jiraInfo );
                }
            }
        }
        //Step4 判断版本状态修改成功时，修改待发布对列表的保留字段1,版本状态为发布状态
        if(SCHEDULED_EXEC_SUCCESS == executeResult){
            ExpectPublishEnqueue oneInfo = expectPublishEnqueueService.enqueueInfoByReportCode(reportCode);
            oneInfo.setReserved1( Integer.toString(SCHEDULED_EXEC_SUCCESS) );
            oneInfo.setUpdateBy( "123");
            oneInfo.setUpdateTime( new Date() );
            return expectPublishEnqueueMapper.updateByPrimaryKeySelective( oneInfo );
        }
        return executeResult;
    }

    @Override
    public List<SelectedVo> getJIRAProjectInfo(){
        //获取所有项目组的项目信息
        List<JiraInfo> jiraInfoList = jiraAPIUtil.getJIRAProjectInfo();
        //前端格式化
        List<SelectedVo> projectList = new CopyOnWriteArrayList<>();
        for(JiraInfo jiraInfo:jiraInfoList){
            SelectedVo selectedVo = new SelectedVo();
            selectedVo.setCode(jiraInfo.getProjectKey());
            selectedVo.setName(jiraInfo.getProjectName());
            projectList.add(selectedVo);
        }
        return projectList;
    }

    @Override
    public int checkJIRAConnection(){
        //获取所有项目组的项目信息
        List<JiraInfo> jiraInfoList = jiraAPIUtil.getJIRAProjectInfo();
        return jiraInfoList.size();
    }
}
